package com.df.bpm.service.impl; 

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.df.bpm.dto.DtoCtrlPlan4requirement;
import com.df.bpm.dto.DtoFailMode4requirement;
import com.df.bpm.entity.*;
import com.df.bpm.mapper.*;
import com.df.common.service.impl.BaseServiceImpl;
import com.df.bpm.dto.DtoRequirement;
import com.df.bpm.dto.DtoRequirementDetails;
import com.df.bpm.service.DtoRequirementService;

import com.df.common.utils.MyQueryWrapper4Like;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class DtoRequirementServiceImpl extends BaseServiceImpl<DtoRequirementMapper,DtoRequirement> implements DtoRequirementService {

    private final RequirementFMMapper requirementFMMapper;
    private final RequirementCPMapper requirementCPMapper;
    private final CtrlPlanMapper ctrlPlanMapper;
    private final CtrlPlanCpFrequencyMapper ctrlPlanCpFrequencyMapper;
    private final CtrlPlanReactionPlanMapper ctrlPlanReactionPlanMapper;
    private final DepartmentMapper departmentMapper;
    private final RoleMapper roleMapper;
    private final RoleDepartmentMapper roleDepartmentMapper;
    private final BusinessMapper businessMapper;
    private final RoleCaseMapper roleCaseMapper;
    private final RequirementMapper requirementMapper;
    private final FailModeMapper failModeMapper;
    private final CpCapacityMapper cpCapacityMapper;
    private final CpFrequencyMapper cpFrequencyMapper;
    private final ReactionPlanMapper reactionPlanMapper;

    public List<DtoRequirement> getList4Like(DtoRequirement temp) {
        if(temp==null){
            return null;
        }
        MyQueryWrapper4Like<DtoRequirement> wrapper=new MyQueryWrapper4Like<>(temp);
        return this.baseMapper.selectList(wrapper.stringLike(temp).orderByDesc("createDate"));
    }

    public DtoRequirementDetails getDtoRequirementDetails(Integer id) {
        DtoRequirementDetails result = new DtoRequirementDetails();
        List<DtoRequirement> dtoRequirements = this.getList4Like(new DtoRequirement().setId(id));

        if (dtoRequirements == null || dtoRequirements.isEmpty()) {
            return result;
        }

        // 设置基础属性（取第一条记录的基础信息）
        DtoRequirement firstRecord = dtoRequirements.get(0);
        result.setId(firstRecord.getId())
                .setRoleCaseId(firstRecord.getRoleCaseId())
                .setValue(firstRecord.getValue())
                .setCreateDate(firstRecord.getCreateDate())
                .setUpdateDate(firstRecord.getUpdateDate())
                .setCreateUser(firstRecord.getCreateUser())
                .setUpdateUser(firstRecord.getUpdateUser())
                .setDpmId(firstRecord.getDpmId())
                .setDpmNameCn(firstRecord.getDpmNameCn())
                .setRoleId(firstRecord.getRoleId())
                .setRoleName(firstRecord.getRoleName())
                .setBusinessId(firstRecord.getBusinessId())
                .setBusinessName(firstRecord.getBusinessName())
                .setFmDesc(firstRecord.getFmDesc())
                .setCpSpec(firstRecord.getCpSpec())
                .setCapacityCn(firstRecord.getCapacityCn())
                .setCapacityEn(firstRecord.getCapacityEn())
                .setFrequencyCn(firstRecord.getFrequencyCn())
                .setFrequencyEn(firstRecord.getFrequencyEn())
                .setReactionPlanCn(firstRecord.getReactionPlanCn())
                .setReactionPlanEn(firstRecord.getReactionPlanEn());

        // 按失效模式ID分组（更准确）
        Map<Integer, List<DtoRequirement>> fmGroup = dtoRequirements.stream()
                .filter(dto -> dto.getFmId() != null)
                .collect(Collectors.groupingBy(DtoRequirement::getFmId));

        List<DtoFailMode4requirement> failModeList = new ArrayList<>();

        // 处理每个失效模式分组
        for (Map.Entry<Integer, List<DtoRequirement>> fmEntry : fmGroup.entrySet()) {
            DtoFailMode4requirement failMode = new DtoFailMode4requirement();
            List<DtoRequirement> fmRecords = fmEntry.getValue();

            if (!fmRecords.isEmpty()) {
                DtoRequirement sample = fmRecords.get(0);
                failMode.setFmId(sample.getFmId())
                        .setFmDesc(sample.getFmDesc());

                // 按控制计划ID分组
                Map<Integer, List<DtoRequirement>> cpGroup = fmRecords.stream()
                        .filter(dto -> dto.getCpId() != null)
                        .collect(Collectors.groupingBy(DtoRequirement::getCpId));

                List<DtoCtrlPlan4requirement> ctrlPlanList = new ArrayList<>();

                // 处理每个控制计划分组
                for (Map.Entry<Integer, List<DtoRequirement>> cpEntry : cpGroup.entrySet()) {
                    DtoCtrlPlan4requirement ctrlPlan = new DtoCtrlPlan4requirement();
                    List<DtoRequirement> cpRecords = cpEntry.getValue();

                    if (!cpRecords.isEmpty()) {
                        DtoRequirement sampleCp = cpRecords.get(0);
                        ctrlPlan.setCpId(sampleCp.getCpId())
                                .setCpSpec(sampleCp.getCpSpec())
                                .setCapacityId(sampleCp.getCapacityId())
                                .setCapacityCn(sampleCp.getCapacityCn());

                        // 构建频率对象列表
                        List<CpFrequency> frequencyList = cpRecords.stream()
                                .filter(dto -> dto.getFrequencyId() != null)
                                .map(dto -> new CpFrequency()
                                        .setId(dto.getFrequencyId())
                                        .setCnDesc(dto.getFrequencyCn())
                                        .setEnDesc(dto.getFrequencyEn()))
                                .distinct()
                                .collect(Collectors.toList());
                        ctrlPlan.setFrequencyList(frequencyList);

                        // 构建反应计划对象列表
                        List<ReactionPlan> reactionPlanList = cpRecords.stream()
                                .filter(dto -> dto.getReactionPlanId() != null)
                                .map(dto -> new ReactionPlan()
                                        .setId(dto.getReactionPlanId())
                                        .setCnDesc(dto.getReactionPlanCn())
                                        .setEnDesc(dto.getReactionPlanEn()))
                                .distinct()
                                .collect(Collectors.toList());
                        ctrlPlan.setReactionPlanList(reactionPlanList);

                        ctrlPlanList.add(ctrlPlan);
                    }
                }

                failMode.setCtrlPlans(ctrlPlanList);
                failModeList.add(failMode);
            }
        }

        result.setDtoFailMode4requirementList(failModeList);

        return result;
    }

    public void updateRelationsByDtoRequirementDetails(DtoRequirementDetails temp) {
        Integer requirementId = temp.getId();
        List<DtoFailMode4requirement> fms = temp.getDtoFailMode4requirementList();

        // 获取数据库中现有的关联关系
        List<RequirementFM> existingRequirementFMs = requirementFMMapper.selectList(
                new QueryWrapper<RequirementFM>().eq("requirementId", requirementId)
        );

        // 处理失效模式关联
        updateRequirementFMs(requirementId, fms, existingRequirementFMs);

        fms.forEach(fm -> {
            List<DtoCtrlPlan4requirement> cps = fm.getCtrlPlans();

            // 获取现有的控制计划关联
            List<RequirementCP> existingRequirementCPs = requirementCPMapper.selectList(
                    new QueryWrapper<RequirementCP>().eq("requirementId", requirementId)
            );

            // 处理控制计划关联
            updateRequirementCPs(requirementId, cps, existingRequirementCPs);

            cps.forEach(cp -> {
                Integer ctrlPlanId = cp.getCpId();

                // 更新控制计划基本信息
                updateCtrlPlanBasicInfo(cp);

                // 处理频率关联
                updateCtrlPlanFrequencies(ctrlPlanId, cp.getFrequencyList());

                // 处理反应计划关联
                updateCtrlPlanReactionPlans(ctrlPlanId, cp.getReactionPlanList());
            });
        });
    }

    /**
     * 更新失效模式关联
     */
    private void updateRequirementFMs(Integer requirementId,
                                      List<DtoFailMode4requirement> newFMs,
                                      List<RequirementFM> existingFMs) {

        // 提取现有的失效模式ID集合
        Set<Integer> existingFMIds = existingFMs.stream()
                .map(RequirementFM::getFailModeId)
                .collect(Collectors.toSet());

        // 提取新的失效模式ID集合
        Set<Integer> newFMIds = newFMs.stream()
                .map(DtoFailMode4requirement::getFmId)
                .collect(Collectors.toSet());

        // 删除不再关联的失效模式
        existingFMs.forEach(existingFM -> {
            if (!newFMIds.contains(existingFM.getFailModeId())) {
                requirementFMMapper.deleteById(existingFM.getId());
            }
        });

        // 新增新关联的失效模式
        newFMs.forEach(newFM -> {
            if (!existingFMIds.contains(newFM.getFmId())) {
                RequirementFM requirementFM = new RequirementFM()
                        .setRequirementId(requirementId)
                        .setFailModeId(newFM.getFmId());
                requirementFMMapper.insert(requirementFM);
            }
        });
    }

    /**
     * 更新控制计划关联
     */
    private void updateRequirementCPs(Integer requirementId,
                                      List<DtoCtrlPlan4requirement> newCPs,
                                      List<RequirementCP> existingCPs) {

        // 提取现有的控制计划ID集合
        Set<Integer> existingCPIds = existingCPs.stream()
                .map(RequirementCP::getCtrlPlanId)
                .collect(Collectors.toSet());

        // 提取新的控制计划ID集合
        Set<Integer> newCPIds = newCPs.stream()
                .map(DtoCtrlPlan4requirement::getCpId)
                .collect(Collectors.toSet());

        // 删除不再关联的控制计划
        existingCPs.forEach(existingCP -> {
            if (!newCPIds.contains(existingCP.getCtrlPlanId())) {
                requirementCPMapper.deleteById(existingCP.getId());
            }
        });

        // 新增新关联的控制计划
        newCPs.forEach(newCP -> {
            if (!existingCPIds.contains(newCP.getCpId())) {
                RequirementCP requirementCP = new RequirementCP()
                        .setRequirementId(requirementId)
                        .setCtrlPlanId(newCP.getCpId());
                requirementCPMapper.insert(requirementCP);
            }
        });
    }

    /**
     * 更新控制计划基本信息（只有发生变动时才更新）
     */
    private void updateCtrlPlanBasicInfo(DtoCtrlPlan4requirement cp) {
        // 先查询数据库中现有的控制计划信息
        CtrlPlan existingCtrlPlan = ctrlPlanMapper.selectById(cp.getCpId());
        if (existingCtrlPlan == null) {
            return; // 如果控制计划不存在，直接返回
        }

        // 检查字段是否发生变动
        boolean hasChanges = isChanges(cp, existingCtrlPlan);

        // 只有当字段发生变动时才执行更新
        if (hasChanges) {
            CtrlPlan updateCtrlPlan = new CtrlPlan()
                    .setId(cp.getCpId())
                    .setSpec(cp.getCpSpec())
                    .setCapacityId(cp.getCapacityId());

            ctrlPlanMapper.updateById(updateCtrlPlan);
        }
    }

    private static boolean isChanges(DtoCtrlPlan4requirement cp, CtrlPlan existingCtrlPlan) {
        // 检查 spec 是否变动
        boolean hasChanges = (cp.getCpSpec() != null && !cp.getCpSpec().equals(existingCtrlPlan.getSpec())) ||
                (cp.getCpSpec() == null && existingCtrlPlan.getSpec() != null);

        // 检查 capacityId 是否变动
        if ((cp.getCapacityId() != null && !cp.getCapacityId().equals(existingCtrlPlan.getCapacityId())) ||
                (cp.getCapacityId() == null && existingCtrlPlan.getCapacityId() != null)) {
            hasChanges = true;
        }
        return hasChanges;
    }

    /**
     * 更新控制计划频率关联
     */
    private void updateCtrlPlanFrequencies(Integer ctrlPlanId, List<CpFrequency> newFrequencies) {
        // 获取现有的频率关联
        List<CtrlPlanCpFrequency> existingFrequencies = ctrlPlanCpFrequencyMapper.selectList(
                new QueryWrapper<CtrlPlanCpFrequency>().eq("ctrlPlanId", ctrlPlanId)
        );

        // 提取现有的频率ID集合
        Set<Integer> existingFrequencyIds = existingFrequencies.stream()
                .map(CtrlPlanCpFrequency::getFrequencyId)
                .collect(Collectors.toSet());

        // 提取新的频率ID集合
        Set<Integer> newFrequencyIds = newFrequencies.stream()
                .map(CpFrequency::getId)
                .collect(Collectors.toSet());

        // 删除不再关联的频率
        existingFrequencies.forEach(existing -> {
            if (!newFrequencyIds.contains(existing.getFrequencyId())) {
                ctrlPlanCpFrequencyMapper.deleteById(existing.getId());
            }
        });

        // 新增新关联的频率
        newFrequencies.forEach(newFreq -> {
            if (!existingFrequencyIds.contains(newFreq.getId())) {
                CtrlPlanCpFrequency ctrlPlanCpFrequency = new CtrlPlanCpFrequency()
                        .setCtrlPlanId(ctrlPlanId)
                        .setFrequencyId(newFreq.getId());
                ctrlPlanCpFrequencyMapper.insert(ctrlPlanCpFrequency);
            }
        });
    }

    /**
     * 更新控制计划反应计划关联
     */
    private void updateCtrlPlanReactionPlans(Integer ctrlPlanId, List<ReactionPlan> newReactionPlans) {
        // 获取现有的反应计划关联
        List<CtrlPlanReactionPlan> existingReactionPlans = ctrlPlanReactionPlanMapper.selectList(
                new QueryWrapper<CtrlPlanReactionPlan>().eq("ctrlPlanId", ctrlPlanId)
        );

        // 提取现有的反应计划ID集合
        Set<Integer> existingReactionPlanIds = existingReactionPlans.stream()
                .map(CtrlPlanReactionPlan::getReactionPlanId)
                .collect(Collectors.toSet());

        // 提取新的反应计划ID集合
        Set<Integer> newReactionPlanIds = newReactionPlans.stream()
                .map(ReactionPlan::getId)
                .collect(Collectors.toSet());

        // 删除不再关联的反应计划
        existingReactionPlans.forEach(existing -> {
            if (!newReactionPlanIds.contains(existing.getReactionPlanId())) {
                ctrlPlanReactionPlanMapper.deleteById(existing.getId());
            }
        });

        // 新增新关联的反应计划
        newReactionPlans.forEach(newRp -> {
            if (!existingReactionPlanIds.contains(newRp.getId())) {
                CtrlPlanReactionPlan ctrlPlanReactionPlan = new CtrlPlanReactionPlan()
                        .setCtrlPlanId(ctrlPlanId)
                        .setReactionPlanId(newRp.getId());
                ctrlPlanReactionPlanMapper.insert(ctrlPlanReactionPlan);
            }
        });
    }

    private DtoRequirementDetails saveDepartment(DtoRequirementDetails temp) {
        if(temp.getDepartment().getId()==null){//部门不存在
            Department dpm=new Department();
            dpm.setNameCn(temp.getDepartment().getNameCn());
            departmentMapper.insert(dpm);//新增部门
            temp.getDepartment().setId(dpm.getId());
        }
        return temp;
    }

    private DtoRequirementDetails saveRole(DtoRequirementDetails temp) {
        if(temp.getRole().getId()==null){//角色不存在
            Role role=new Role();
            role.setName(temp.getRole().getName());
            roleMapper.insert(role);//新增角色
            temp.getRole().setId(role.getId());
            RoleDepartment roleDepartment=new RoleDepartment();
            roleDepartment.setDepartmentId(temp.getDepartment().getId());
            roleDepartment.setRoleId(role.getId());
            roleDepartmentMapper.insert(roleDepartment);//角色部门关联
        }
        return temp;
    }

    private DtoRequirementDetails saveDtoRoleCase(DtoRequirementDetails temp) {
        if(temp.getBusiness().getId()==null){//业务不存在
            Business business=new Business();
            business.setName(temp.getBusiness().getName());
            businessMapper.insert(business);//新增业务
            temp.getBusiness().setId(business.getId());
            RoleCase roleCase=new RoleCase();
            roleCase.setRoleId(temp.getRole().getId());
            roleCase.setBusinessId(business.getId());
            roleCaseMapper.insert(roleCase);//业务角色关联
            temp.getBusiness().setRoleCaseId(roleCase.getId());
            temp.setRoleCaseId(roleCase.getId());
        }
        return temp;
    }

    private Requirement newRequirement(DtoRequirementDetails temp) {
        Requirement requirement=new Requirement();
        requirement.setRoleCaseId(temp.getBusiness().getRoleCaseId());
        requirement.setValue(temp.getValue());
        requirementMapper.insert(requirement);
        temp.setId(requirement.getId());
        return requirement;
    }

    private Requirement updateRequirement(DtoRequirementDetails temp) {
        Requirement requirement=new Requirement();
        requirement.setRoleCaseId(temp.getBusiness().getRoleCaseId());
        requirement.setValue(temp.getValue());
        requirement.setId(temp.getId());
        requirementMapper.updateById(requirement);
        return requirement;
    }

    private Requirement saveRequirement(DtoRequirementDetails temp) {
        DtoRequirementDetails temp1=saveDepartment(temp);
        DtoRequirementDetails temp2=saveRole(temp1);
        DtoRequirementDetails temp3=saveDtoRoleCase(temp2);
        if(temp.getId()==null){//申请单不存在
            return newRequirement(temp3);//新增申请单
        }else{
            return updateRequirement(temp3);//更改申请单
        }
    }

    private boolean checkFailModeChanged(FailMode oldFailMode, FailMode newFailMode) {
        if (oldFailMode == null || newFailMode == null) {
            return oldFailMode != newFailMode;
        }
        // 逐字段比较
        return !(Objects.equals(oldFailMode.getRoleCaseId(), newFailMode.getRoleCaseId()) &&
                Objects.equals(oldFailMode.getModeDesc(), newFailMode.getModeDesc()));
    }

    private FailMode saveDtoFailMode4requirement(Requirement requirement, DtoFailMode4requirement dtoFm) {
        FailMode failMode=new FailMode();
        failMode.setRoleCaseId(requirement.getRoleCaseId());
        failMode.setModeDesc(dtoFm.getFmDesc());
        if(dtoFm.getFmId()==null){
            failModeMapper.insert(failMode);
            dtoFm.setFmId(failMode.getId());
        }else {
            failMode.setId(dtoFm.getFmId());
            FailMode oFm=failModeMapper.selectById(dtoFm.getFmId());
            boolean isChanged=checkFailModeChanged(oFm,failMode);
            if(isChanged){
                failModeMapper.updateById(failMode);
            }
        }
        return failMode;
    }

    private void saveRequirementFM(Requirement requirement, List<DtoFailMode4requirement> failModes) {
        List<RequirementFM> oShips=requirementFMMapper.selectListByRequirementId(requirement.getId());
        List<Integer> newFmIds = failModes.stream()
                .map(DtoFailMode4requirement::getFmId)
                .distinct()  // 去除重复元素
                .sorted()    // 排序（默认升序）
                .collect(Collectors.toList());
        List<Integer> oldFmIds = new ArrayList<>();
        oShips.forEach(ship->{
            if(newFmIds.contains(ship.getFailModeId())){
                oldFmIds.add(ship.getFailModeId());
            }else{
                requirementFMMapper.deleteById(ship);
            }
        });
        failModes.forEach(fm->{
            if(fm.getFmId()!=null && !oldFmIds.contains(fm.getFmId())){
                requirementFMMapper.insert(
                        new RequirementFM()
                                .setRequirementId(requirement.getId())
                                .setFailModeId(fm.getFmId())
                );
            }
        });
    }

    private boolean checkCtrlPlanChanged(CtrlPlan oCtrlPlan, CtrlPlan newCtrlPlan) {
        if (oCtrlPlan == null || newCtrlPlan == null) {
            return oCtrlPlan != newCtrlPlan;
        }
        // 逐字段比较
        return !(Objects.equals(oCtrlPlan.getFailModeId(), newCtrlPlan.getFailModeId()) &&
                Objects.equals(oCtrlPlan.getCapacityId(), newCtrlPlan.getCapacityId()) &&
                Objects.equals(oCtrlPlan.getSpec(), newCtrlPlan.getSpec()));
    }

    private CtrlPlan saveDtoCtrlPlan4requirement(FailMode fm, DtoCtrlPlan4requirement dtoCp) {
        CpCapacity cpCapacity=new CpCapacity();
        cpCapacity.setCnDesc(dtoCp.getCapacityCn());
        if(dtoCp.getCapacityId()==null){
            cpCapacityMapper.insert(cpCapacity);
            dtoCp.setCapacityId(cpCapacity.getId());
        }
        CtrlPlan ctrlPlan=new CtrlPlan();
        ctrlPlan.setFailModeId(fm.getId());
        ctrlPlan.setSpec(dtoCp.getCpSpec());
        ctrlPlan.setCapacityId(dtoCp.getCapacityId());
        if(dtoCp.getCpId()==null){
            ctrlPlanMapper.insert(ctrlPlan);
            dtoCp.setCpId(ctrlPlan.getId());
        }else{
            ctrlPlan.setId(dtoCp.getCpId());
            CtrlPlan oCtrlPlan=ctrlPlanMapper.selectById(dtoCp.getCpId());
            boolean isChanged=checkCtrlPlanChanged(oCtrlPlan,ctrlPlan);
            if(isChanged){
                ctrlPlanMapper.updateById(ctrlPlan);
            }
        }
        return ctrlPlan;
    }

    private void saveRequirementCP(Requirement requirement, List<DtoCtrlPlan4requirement> ctrlPlans) {
        List<RequirementCP> oShips=requirementCPMapper.selectListByRequirementId(requirement.getId());
        List<Integer> newCpIds = ctrlPlans.stream()
                .map(DtoCtrlPlan4requirement::getCpId)
                .distinct()  // 去除重复元素
                .sorted()    // 排序（默认升序）
                .collect(Collectors.toList());
        List<Integer> oldCpIds = new ArrayList<>();
        oShips.forEach(ship->{
            if(newCpIds.contains(ship.getCtrlPlanId())){
                oldCpIds.add(ship.getCtrlPlanId());
            }else{
                requirementCPMapper.deleteById(ship);
            }
        });
        ctrlPlans.forEach(cp->{
            if(cp.getCpId()!=null && !oldCpIds.contains(cp.getCpId())){
                requirementCPMapper.insert(
                        new RequirementCP()
                                .setRequirementId(requirement.getId())
                                .setCtrlPlanId(cp.getCpId())
                );
            }
        });
    }

    private void saveFrequency(CtrlPlan cp, List<CpFrequency> fqs) {
        List<CtrlPlanCpFrequency> oldFqs=ctrlPlanCpFrequencyMapper.selectListByCpId(cp.getId());
        List<Integer> oldFqIds = oldFqs.stream()
                .map(CtrlPlanCpFrequency::getFrequencyId)
                .distinct()  // 去除重复元素
                .sorted()    // 排序（默认升序）
                .collect(Collectors.toList());
        List<Integer> newFqIds=new ArrayList<>();
        fqs.forEach(fq->{
            if(fq.getId()==null){
                cpFrequencyMapper.insert(fq);
            }
            newFqIds.add(fq.getId());
            if(!oldFqIds.contains(fq.getId())){
                ctrlPlanCpFrequencyMapper.insert(
                        new CtrlPlanCpFrequency()
                                .setCtrlPlanId(cp.getId())
                                .setFrequencyId(fq.getId())
                );
            }
        });
        oldFqs.forEach(ofq->{
            if(!newFqIds.contains(ofq.getFrequencyId())){
                ctrlPlanCpFrequencyMapper.deleteById(ofq);
            }
        });
    }

    private void saveReactionPlan(CtrlPlan cp, List<ReactionPlan> rps) {
        List<CtrlPlanReactionPlan> oldRps=ctrlPlanReactionPlanMapper.selectListByCpId(cp.getId());
        List<Integer> oldRpIds = oldRps.stream()
                .map(CtrlPlanReactionPlan::getReactionPlanId)
                .distinct()  // 去除重复元素
                .sorted()    // 排序（默认升序）
                .collect(Collectors.toList());
        List<Integer> newRpIds=new ArrayList<>();
        rps.forEach(rp->{
            if(rp.getId()==null){
                reactionPlanMapper.insert(rp);
            }
            newRpIds.add(rp.getId());
            if(!oldRpIds.contains(rp.getId())){
                ctrlPlanReactionPlanMapper.insert(
                        new CtrlPlanReactionPlan()
                                .setCtrlPlanId(cp.getId())
                                .setReactionPlanId(rp.getId())
                );
            }
        });
        oldRps.forEach(orp->{
            if(!newRpIds.contains(orp.getReactionPlanId())){
                ctrlPlanReactionPlanMapper.deleteById(orp);
            }
        });
    }

    /**
     * 保存申请单详情
     * @param temp 申请单详情
     */
    public void saveDtoRequirementDetails(DtoRequirementDetails temp) {
        Requirement requirement=saveRequirement(temp);
        List<DtoCtrlPlan4requirement> iCtrlPlans=new ArrayList<>();
        temp.getDtoFailMode4requirementList().forEach(dtoFm->{
            FailMode fm=saveDtoFailMode4requirement(requirement,dtoFm);
            dtoFm.getCtrlPlans().forEach(dtoCp->{
                CtrlPlan cp=saveDtoCtrlPlan4requirement(fm,dtoCp);
                saveFrequency(cp,dtoCp.getFrequencyList());
                saveReactionPlan(cp,dtoCp.getReactionPlanList());
            });
            iCtrlPlans.addAll(dtoFm.getCtrlPlans());
        });
        saveRequirementCP(requirement,iCtrlPlans);
        saveRequirementFM(requirement,temp.getDtoFailMode4requirementList());
    }
}